<script lang="ts" setup>
import { MemberDynamicBonu, mode2TextMap, mode2UnitMap, modeAndValueRules } from '../common'

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const formData = ref(JSON.parse(props.modelValue || '{}') as MemberDynamicBonu)
watch(
  () => props.modelValue,
  (value) => {
    formData.value = JSON.parse(value || '{}')
  }
)
watch(
  formData,
  (value) => {
    // value.value = Number(value.value)

    console.log(value)
    if (value && Object.keys(value).length > 0) {
      const newVal = { ...value, value: Number(value.value) }
      const str = JSON.stringify(newVal)
      emit('update:modelValue', str)
    } else {
      emit('update:modelValue', JSON.stringify(value))
    }
  },
  { deep: true }
)

const handleModeChange = () => {
  formData.value.value = 0
}

const formRules = computed(() => ({
  ...modeAndValueRules(formData.value.mode),
  delay: [{ required: true, message: '请输入分润延迟时间', trigger: 'blur' }]
}))

const formLoading = ref(false)

// 是否初始化
const inited = computed(() => JSON.stringify(formData.value) !== '{}')
// 初始化事件
const handleInit = () => {
  formData.value = { mode: 'amount', value: 0, delay: 0 }
}
// 删除
const handleDelete = () => {
  formData.value = {} as MemberDynamicBonu
}
</script>

<template>
  <!-- 待初始化 -->
  <div v-if="!inited" class="flex justify-center">
    <el-button type="primary" @click="handleInit">添加</el-button>
  </div>

  <!-- 表单 -->
  <el-form
    v-else
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="120px"
    v-loading="formLoading"
  >
    <el-form-item label="分润模式" prop="mode">
      <el-radio-group v-model="formData.mode" @change="handleModeChange">
        <el-radio-button :label="key" v-for="(text, key) in mode2TextMap" :key="key">
          {{ text }}
        </el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item :label="`分润${mode2TextMap[formData.mode]}`" prop="value">
      <el-input
        class="w-20"
        v-model="formData.value"
        type="number"
        :placeholder="`请输入分润${mode2TextMap[formData.mode]}`"
      />
      <span class="inline-block ml-2">{{ mode2UnitMap[formData.mode] }}</span>
    </el-form-item>
    <!-- <el-form-item label="分润延迟时间" prop="delay">
      <el-input class="w-20" v-model="formData.delay" placeholder="请输入分润延迟时间" />
      <span class="inline-block ml-2">天</span>
    </el-form-item> -->
    <div class="flex justify-end">
      <el-button type="danger" @click="handleDelete">删除</el-button>
    </div>
  </el-form>
</template>
